// proxyUsageRateDetail.js
import * as echarts from '../../miniprogram_npm/ec-canvas/echarts';

const app = getApp()
const util = require("../../utils/util.js")
var gaugeChart = null;
var lineChart = null;
var barChart = null;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    timeList: [],
    timeSelect: 29,//选择的时间列表下标
    timeWidth: '',

    selectShow: false,//控制下拉列表的显示隐藏，false隐藏、true显示
    selectData: ['天', '月'],//下拉列表的数据
    selectindex: 0,//选择的下拉列表下标

    "rate": [],// 店铺使用率排行 (前7位)
    "orderCount": [],// 订单分时数量
    "least": [],// 使用率最低
    "weekly": [],// 7 天内使用率
    "info": {}, // 店铺信息
    expand: true,

    ecgauge: {
      // onInit: initGaugeChart,
      lazyLoad: true
    },
    ecline: {
      // onInit: initGaugeChart,
      lazyLoad: true
    },
    ecbar: {
      // onInit: initGaugeChart,
      lazyLoad: true
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      id: options.id,
      openid: options.openid,
      timeSelect: options.timeSelect,
      selectindex: options.selectindex
    })
    if(options.selectindex==1){
      this.arrayMonth(options.timeSelect);
    }else{
      this.arrayDay(options.timeSelect);
    }
    this.gaugeechartsComponnet = this.selectComponent('#mychart-dom-gauge');
    this.lineechartsComponnet = this.selectComponent('#mychart-dom-line');
    this.barechartsComponnet = this.selectComponent('#mychart-dom-bar');

    this.useList();
  },
  onUnload:function(){
    gaugeChart = null;
    lineChart = null;
    barChart = null;
  },
  useList:function(){
    var that = this;
    var type = that.data.selectindex == 0 ? 'day' : 'month';
    var id = that.data.id;
    var openid = that.data.openid;
    var data = {
      date:that.data.timeList[that.data.timeSelect].value,
      type:type,
      id:id,
      openid:openid
    };
    
    app.post('agent/usageAnalysisByShopInfo',data).then((res)=>{
      if (res.code == 200) {
        that.setData({
          info: res.data.info,
          weekly: res.data.weekly,
          least: res.data.least,
          orderCount: res.data.orderCount,
          rate: res.data.rate,
        })
        gaugeChart = null;
        lineChart = null;
        barChart = null;

        if(that.data.orderCount !== null || that.data.orderCount.length !== 0){
          if (!lineChart) {
            this.initLineChart()
          } else {
            this.setOptionLine(lineChart)
          }
        }
        if (!barChart) {
          this.initBarChart()
        } else {
          this.setOptionBar(barChart)
        }
        if (!gaugeChart) {
          this.initGaugeChart()
        } else {
          this.setOptionGauge(gaugeChart)
        }
      }
    }).catch((errMsg)=>{
      console.log(errMsg);
      wx.showToast({
        title: "网络错误",
        icon: 'loading',
        duration: 2000
      })
    })
  },
  // 设备列表
  ToDeviceTap: function () {
    var id = this.data.id;
    wx.navigateTo({
      url: '../../pages/proxySubShopDevice/proxySubShopDevice?id=' + id,
    })
  },
  // 展开收起设备订单列表
  expandTap:function(){
    var that = this;
    that.setData({
      expand: !that.data.expand
    })
  },
  // 获取时间列表的长度
  timeWidth: function () {
    var query = wx.createSelectorQuery();
    var that = this;
    query.select('.timelist').boundingClientRect(function (rect) {
      that.setData({
        timeWidth: rect.width,
      })
    }).exec();
  },
  // 切换时间
  timeChoose: function (e) {
    var that = this;
    var index = e.target.dataset.timeindex;
    if (that.data.timeSelect == index) { return false; }
    else {
      that.setData({
        timeSelect: index
      })
      that.useList();
    }
  },
  // 点击下拉显示框
  selectTap() {
    this.setData({
      selectShow: !this.data.selectShow
    });
  },
  // 点击下拉列表
  optionTap(e) {
    let index = e.currentTarget.dataset.index;//获取点击的下拉列表的下标
    this.setData({
      selectindex: index,
      selectShow: !this.data.selectShow
    });
    if (index == 0) {
      this.arrayDay()
    } else if (index == 1) {
      this.arrayMonth()
    }
    this.useList();

  },
  // 获取当前日期的前30天（不包括当天）
  arrayDay: function (timeSelect) {
    var array_d = [];
    var obj = {}
    for (var i = 0; i < 30; i++) {
      var arr = util.formatdate(new Date(new Date().setDate(new Date().getDate() - i)))
      obj = {
        value: arr,
        key: arr.substring(8, 10)
      }
      array_d.unshift(obj)
    }
    this.setData({
      timeList: array_d,
      timeSelect: timeSelect || 29
    })
    this.timeWidth();
  },
  // 获取当前日期的前12月（不包括当月）
  arrayMonth: function (timeSelect) {
    var array_d = [];
    var obj = {}
    var d = new Date();
    for (var i = 0; i < 12; i++) {
      var m = d.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      obj = {
        value: d.getFullYear() + "-" + m,
        key: m.toString()
      }
      d.setMonth(d.getMonth() - 1);
      array_d.unshift(obj)
    }
    this.setData({
      timeList: array_d,
      timeSelect: timeSelect || 11
    })
    this.timeWidth();
  },
  // 使用率仪表盘建立
  initGaugeChart: function () {
    this.gaugeechartsComponnet.init((canvas, width, height) => {
      // 初始化图表
      gaugeChart = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      // Chart.setOption(this.getOption());
      this.setOptionGauge(gaugeChart);
      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return gaugeChart;
    });
  },
  setOptionGauge: function (Chart) {
    Chart.clear();  // 清除
    Chart.setOption(this.getGauge(), true);  //获取新数据
  },
  getGauge: function() {
    var that = this; 
    // var rate = Math.round((that.data.info.rate * 100) * 100) / 100;
    // var rate = parseFloat( (that.data.info.rate * 100).toFixed(2) );
    var rate = that.data.info.rate;
    var name = that.data.selectindex == 0 ? '当天使用率' :'当月使用率';
    var color = [];
    if (rate < 1){
      color = [
        [rate, '#F08519'],
        [1, '#E6E6E6']
      ]
    }else{
      color = [
        [1, '#F08519']
      ]
    }
    var option = {
      series: [{
        name: name,
        type: 'gauge',
        radius: '100%',
        axisLine: {//仪表盘轴线相关配置
          show: true,
          lineStyle: {
            width: 10,
            shadowBlur: 0,
            color: color,
          }
        },
        splitLine: {//分隔线样式
          show: false
        },
        axisTick: {//刻度样式
          show: false
        },
        axisLabel: {//刻度标签
          show: true,
          distance: -17,
          color: "#b3b3b3",
          fontSize: 14,
        },
        pointer: {//仪表盘指针
          show: false
        },
        title: {//仪表盘标题
          offsetCenter: [0, '40%'],
          color: "#b3b3b3",
          fontSize: 15,
        },
        detail: {
          color: "#f08519",
          fontWeight: 'lighter',
          fontSize: 16,
          offsetCenter: [0, 0],

          formatter: [
            '{a|{value}}%'
          ].join('\n'),
          rich: {
            a: {
              fontSize: 36
            }
          },
        },
        data: [{
          value: that.data.info.formatRate,
          name: name
        }]
      }]
    };
    return option;
  },
  // 订单数折线图建立
  initLineChart: function () {
    this.lineechartsComponnet.init((canvas, width, height) => {
      // 初始化图表
      lineChart = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      // Chart.setOption(this.getOption());
      this.setOptionLine(lineChart);
      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return lineChart;
    });
  },
  setOptionLine: function (Chart) {
    Chart.clear();  // 清除
    Chart.setOption(this.getLine(),true);  //获取新数据
  },
  getLine: function() {
    var that = this;
    var orderCount = that.data.orderCount;
    var date = [];
    var num =[];
    for (var i = 0; i < orderCount.length;i++){
      date.push(orderCount[i].date);
      num.push(orderCount[i].num)
    }
    var option = {
      color: ["#f08519"],
      // legend: {//图例组件
      //   data: ['订单数'],
      //   top: 0,
      //   left: 20,
      //   z: 100,
      //   selectedMode :false,
      //   icon: 'roundRect'
      // },
      tooltip: {//提示框
        show: true,
        trigger: 'axis',
        // position: ['40%', '0%'],
        formatter: '订单数:{c}',
        axisPointer: {
          type: 'none'
        },
        showContent: false
      },
      grid:{
        x: '-5%', y: '20%', width: '105%', height: '80%', containLabel: true
      },
      xAxis: {
        position:"bottom",
        type: 'category',
        boundaryGap: true,
        min:'dataMin',
        data: date,
        axisLine:{
          show: false
        },
        axisTick:{
          show:false
        },
      },
      yAxis: {
        show: false
      },
      series: [{
        name: '订单数',
        type: 'line',
        smooth: true,
        data: num,
        clipOverflow :false,
        showSymbol: false,
        symbolSize:6,
        sampling :'average',
        itemStyle:{
          normal:{
            borderWidth:2
          }
        },
        label: {
          normal: {
            show: true,
            position: 'top',
            formatter: '{c}',
            fontSize: 18,
          }
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
            offset: 0,
            color: 'rgba(240, 133, 25,.2)'
          }, {
            offset: 1,
              color: 'rgba(240, 133, 25,0)'
          }]),
        },
      }]
    };
    return option;
  },
  // 店铺近7天使用率柱状图建立
  initBarChart: function () {
    this.barechartsComponnet.init((canvas, width, height) => {
      // 初始化图表
      barChart = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      // Chart.setOption(this.getOption());
      this.setOptionBar(barChart);
      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return barChart;
    });
  },
  setOptionBar: function (Chart) {
    Chart.clear();  // 清除
    Chart.setOption(this.getBar(),true);  //获取新数据
  },
  getBar:function(){
    var that = this;
    var weekly = that.data.weekly;
    var rate = [];
    var time = [];
    var name = that.data.selectindex == 0 ? '店铺近7天使用率：':'店铺本月使用率：';
    for (var i = 0; i < weekly.length; i++) {
      rate.push(weekly[i].rate*100);
      time.push(weekly[i].time.substring(8,10));
    }
    var option = {
      color: ['#f08519'],
      tooltip: {show: false},
      grid: {
        left: 15,
        right: 30,
        bottom: 15,
        top: 25,
        containLabel: true
      },
      yAxis: {
        type: 'category',
        name: '/日',
        nameTextStyle :{
          color:'#4d4d4d',
          padding: [30, 30, 0, 0]
        },
        nameGap :0,
        axisTick: { show: false },
        data: time,
        axisLine: {
          lineStyle: {
            color: '#e6e6e6'
          }
        },
        axisLabel: {
          color: '#4d4d4d'
        }
      }
      ,
      xAxis:{
        type: 'value',
        name: '/%',
        nameTextStyle: {
          color: '#4d4d4d',
          padding: [40, 0, 0, 15]
        },
        nameGap: -5,
        axisTick: { show: false },
        axisLine: { show: false },
        axisLabel: {
          color: '#4d4d4d',
          margin :14
        },
        splitLine :{
          lineStyle:{
            color: '#e6e6e6'
          }
        }
      }
      ,
      series: [
        {
          name: name,
          type: 'bar',
          label: {
            normal: {
              show: true,
              position: 'right',
              color:'#F08519',
              distance:5,
            }
          },
          data: rate,
          itemStyle:{
            barBorderRadius :4
          },
          emphasis: {
            label: {
              color: '#E62129'
            },
            itemStyle: {
              color: '#E62129'
            }
          },
          barWidth :20
        }
      ]
    };
    return option;
  }
})